package cn.z2huo.productcenter.management.app.code;

import cn.z2huo.productcenter.management.enums.CodeTypeEnum;
import cn.z2huo.productcenter.util.SnowflakeGenerateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Objects;

/**
 * <p>
 *
 * @author z2huo
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SnowflakeCodeGenerator implements CodeGenerator {

    /**
     * <p>生成业务代码
     * <p>业务类型拼接雪花算法，有顺序，但是长度不固定
     *
     * @param typeEnum  业务代码类型
     */
    @Override
    public String generate(CodeTypeEnum typeEnum) {
        Assert.notNull(typeEnum, "业务代码类型不能为空");
        try {
            String code = typeEnum.getValue() + SnowflakeGenerateUtils.getSnowflake(SNOWFLAKE_KEY).nextIdStr();
            return Objects.requireNonNull(code);
        } catch (Exception e) {
            log.error("生成业务代码失败，类型为 {}", typeEnum.getValue(), e);
            throw e;
        }
    }

}
